package com.frank.test.lock;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest2 {

    int count = 0;
    ReentrantLock lock = new ReentrantLock();
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    @Test
    public void t1() {

        Thread thread1 = new Thread(new Provider());
        Thread thread2 = new Thread(new Consumer());

        thread1.start();
        thread2.start();

        while (true) {

        }
    }

    class Provider implements Runnable {

        @Override
        public void run() {

            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    lock.lock();
                    System.out.println("Provider 获得锁'");
                    while (count > 6) {
                        c1.await();
                    }
                    count++;
                    System.out.println(Thread.currentThread().getName()+ "__新增： " + count);
                    c2.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                    System.out.println("Provider 释放锁'");
                }
            }

        }
    }

    class Consumer implements Runnable {

        @Override
        public void run() {

            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    lock.lock();
                    System.out.println("Consumer 获得锁'");
                    while (count <= 0) {
                        c2.await();
                    }
                    count--;
                    System.out.println(Thread.currentThread().getName()+ "__消费： " + count);
                    c1.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                    System.out.println("Consumer 释放锁'");
                }
            }
        }
    }
}
